<!-- eslint-disable vue/valid-v-slot -->
<!-- eslint-disable vue/no-lone-template -->
<template>
  <div class="main-container">
    <TableBody>
      <template #header>
        <TableHeader ref="tableHeaderRef" :show-filter="false">
          <template #search-content>
            <a-form ref="seachForm" :model="form">
              <a-row :gutter="24">
                <a-col :span="4">
                  <a-form-item field="channelId" hide-label>
                    <a-select
                      class="width100"
                      v-model="form.channelId"
                      placeholder="请选择渠道"
                      allow-clear
                    >
                      <a-option v-for="item in channel" :key="item.id" :value="item.id">{{
                        item.name
                      }}</a-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="state" hide-label>
                    <a-select
                      class="width100"
                      v-model="form.state"
                      placeholder="请选择轮询状态"
                      allow-clear
                    >
                      <a-option :value="0">轮询完成</a-option>
                      <a-option :value="1">轮询超时</a-option>
                      <a-option :value="2">轮询取消</a-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="pollingTime" hide-label>
                    <a-select
                      class="width100"
                      v-model="form.pollingTime"
                      placeholder="请选择轮询时间"
                      allow-clear
                    >
                      <a-option :value="0">1分钟执行一次</a-option>
                      <a-option :value="1">5分钟执行一次</a-option>
                      <a-option :value="2">10分钟执行一次</a-option>
                      <a-option :value="3">20分钟执行一次</a-option>
                      <a-option :value="4">30分钟执行一次</a-option>
                      <a-option :value="5">1小时执行一次</a-option>
                      <a-option :value="6">3小时执行一次</a-option>
                      <a-option :value="7">6小时执行一次</a-option>
                      <a-option :value="8">8小时执行一次</a-option>
                      <a-option :value="9">12小时执行一次</a-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <!-- <a-col :span="4">
                  <a-form-item field="addAddTime" hide-label>
                    <a-date-picker
                      class="width100"
                      v-model="form.addAddTime"
                      show-time
                      :disabledDate="changeTraceEnd"
                      placeholder="请选择开始轮询时间"
                      :time-picker-props="{ defaultValue: '12:00:00' }"
                      format="YYYY-MM-DD HH:mm:ss"
                      :shortcuts="[
                        {
                          label: '今日',
                          value: () => (
                            (form.addAddTime = $dayjs('00:00:00', 'HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            )),
                            (form.endAddTime = $dayjs('23:59:59', 'HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            ))
                          ),
                        },
                        {
                          label: '昨日',
                          value: () => (
                            (form.addAddTime = $dayjs('00:00:00', 'HH:mm:ss')
                              .subtract(1, 'day')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (form.endAddTime = $dayjs('23:59:59', 'HH:mm:ss')
                              .subtract(1, 'day')
                              .format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '七日',
                          value: () => (
                            (form.addAddTime = $dayjs('00:00:00', 'HH:mm:ss')
                              .subtract(6, 'day')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (form.endAddTime = $dayjs().format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '本月',
                          value: () => (
                            (form.addAddTime = $dayjs('01 00:00:00', 'DD HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            )),
                            (form.endAddTime = $dayjs().format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '上月',
                          value: () => (
                            (form.addAddTime = $dayjs(`01 00:00:00`, 'DD HH:mm:ss')
                              .subtract(1, 'month')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (form.endAddTime = $dayjs()
                              .subtract(1, 'month')
                              .endOf('month')
                              .format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                      ]"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="endAddTime" hide-label>
                    <a-date-picker
                      class="width100"
                      v-model="form.endAddTime"
                      show-time
                      :disabledDate="changeTraceStart"
                      placeholder="请选择结束轮询时间"
                      :time-picker-props="{ defaultValue: '12:00:00' }"
                      :shortcuts="[
                        {
                          label: '今日',
                          value: () => (
                            (form.addAddTime = $dayjs('00:00:00', 'HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            )),
                            (form.endAddTime = $dayjs('23:59:59', 'HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            ))
                          ),
                        },
                        {
                          label: '昨日',
                          value: () => (
                            (form.addAddTime = $dayjs('00:00:00', 'HH:mm:ss')
                              .subtract(1, 'day')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (form.endAddTime = $dayjs('23:59:59', 'HH:mm:ss')
                              .subtract(1, 'day')
                              .format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '七日',
                          value: () => (
                            (form.addAddTime = $dayjs('00:00:00', 'HH:mm:ss')
                              .subtract(6, 'day')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (form.endAddTime = $dayjs().format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '本月',
                          value: () => (
                            (form.addAddTime = $dayjs('01 00:00:00', 'DD HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            )),
                            (form.endAddTime = $dayjs().format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '上月',
                          value: () => (
                            (form.addAddTime = $dayjs(`01 00:00:00`, 'DD HH:mm:ss')
                              .subtract(1, 'month')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (form.endAddTime = $dayjs()
                              .subtract(1, 'month')
                              .endOf('month')
                              .format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                      ]"
                    />
                  </a-form-item>
                </a-col> -->
                <a-col :span="4">
                  <a-form-item hide-label>
                    <a-input-group class="width100">
                      <a-input v-model="form.addSuccess" placeholder="开始成功数量" />
                      <a-input v-model="form.endSuccess" placeholder="结束成功数量" />
                    </a-input-group>
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item hide-label>
                    <a-input-group class="width100">
                      <a-input v-model="form.addError" placeholder="开始失败数量" />
                      <a-input v-model="form.endError" placeholder="结束失败数量" />
                    </a-input-group>
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item hide-label>
                    <a-input-group class="width100">
                      <a-input v-model="form.addPollingThread" placeholder="开始线程数量" />
                      <a-input v-model="form.endPollingThread" placeholder="结束线程数量" />
                    </a-input-group>
                  </a-form-item>
                </a-col>
                <a-col :span="4" :offset="20">
                  <a-form-item content-class=" flex justify-end" field="btns" hide-label>
                    <a-space :size="15">
                      <a-button
                        type="primary"
                        v-permission="getPollingLog"
                        html-type="submit"
                        @click="doRefresh(1)"
                        ><template #icon> <icon-search /> </template>搜索</a-button
                      >
                      <a-button v-permission="getPollingLog" @click="resetSeach"
                        ><template #icon>
                          <icon-sync theme="outline" size="14" />
                        </template>
                        <!-- Use the default slot to avoid extra spaces -->
                        <template #default>重置</template></a-button
                      >
                    </a-space>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </template>
        </TableHeader>
      </template>
      <template #table-config>
        <a-space :size="15">
          <a-button
            type="outline"
            v-permission="getPollingLogs"
            @click="exportExcelLists"
            :loading="loading"
          >
            <!-- Use the default slot to avoid extra spaces -->
            <template #default>导出</template>
          </a-button>
        </a-space>
        <a-space :size="15">
          <TableConfig
            @update-border="onUpdateBorder"
            @update-striped="onUpdateStriped"
            @refresh="doRefresh"
          />
        </a-space>
      </template>
      <template #default>
        <a-table
          :bordered="{ wrapper: true, cell: tables.bordered }"
          :stripe="(tables.striped as boolean)"
          :loading="tables.tableLoading"
          :data="table.dataList"
          :pagination="false"
          :column-resizable="true"
          :rowKey="rowKey"
          :columns="tableColumns.list"
          table-layout-fixed
          hide-expand-button-on-empty
          :default-expand-all-rows="true"
          :scroll="{ x: 1500 }"
        >
          <template #columns>
            <a-table-column
              v-for="item of tableColumns.list"
              :key="item.key"
              align="left"
              :title="(item.title as string)"
              :width="item.width"
              :data-index="(item.key as string)"
              :fixed="item.fixed"
              :ellipsis="true"
              :tooltip="true"
            >
              <template v-if="item.key === 'total'" #cell="{ record }">
                <a-space>
                  <a-button size="small" type="text" class="butten">
                    {{ record.total }} 张
                  </a-button>
                </a-space>
              </template>
              <template v-if="item.key === 'state'" #cell="{ record }">
                <a-space>
                  <a-tag v-if="record.state == 1" color="gold">轮询超时</a-tag>
                  <a-tag v-else-if="record.state == 2" color="red">轮询取消</a-tag>
                  <a-tag v-else color="blue">轮询完成</a-tag>
                </a-space>
              </template>
              <template v-if="item.key === 'pollingTime'" #cell="{ record }">
                <div v-if="record.pollingTime == 0">1分钟轮询一次</div>
                <div v-if="record.pollingTime == 1">5分钟轮询一次</div>
                <div v-if="record.pollingTime == 2">10分钟轮询一次</div>
                <div v-if="record.pollingTime == 3">20分钟轮询一次</div>
                <div v-if="record.pollingTime == 4">30分钟轮询一次</div>
                <div v-if="record.pollingTime == 5">1小时轮询一次</div>
                <div v-if="record.pollingTime == 6">3小时轮询一次</div>
                <div v-if="record.pollingTime == 7">6小时轮询一次</div>
                <div v-if="record.pollingTime == 8">8小时轮询一次</div>
                <div v-if="record.pollingTime == 9">12小时轮询一次</div>
              </template>
              <template v-if="item.key === 'channelId'" #cell="{ record }">
                {{ record.channel.name }}
              </template>
              <template v-if="item.key === 'time'" #cell="{ record }">
                {{ userCommon.getTimeDifferences(record.addTime, record.endTime) }}
              </template>
              <template v-if="item.key === 'pollingThread'" #cell="{ record }">
                {{ record.pollingThread }}个
              </template>
              <template v-if="item.key === 'probability'" #cell="{ record }">
                {{ Math.floor((record.success / (record.error + record.success)) * 100) }}%
              </template>
              <template v-if="item.key === 'total'" #cell="{ record }">
                <a-space>
                  <a-button size="small" type="text" class="butten">
                    {{ record.success + record.error }} 张
                  </a-button>
                </a-space>
              </template>
              <template v-if="item.key === 'success'" #cell="{ record }">
                <a-space>
                  <a-button size="small" type="text" class="butten">
                    {{ record.success }} 张
                  </a-button>
                </a-space>
              </template>
              <template v-if="item.key === 'error'" #cell="{ record }">
                <a-space>
                  <a-button size="small" type="text" class="butten">
                    {{ record.error }} 张
                  </a-button>
                </a-space>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </template>
      <template #footer>
        <TableFooter ref="tableFooterRef" :pagination="pagination" />
      </template>
    </TableBody>
    <a-modal v-model:visible="visible" width="70%" hide-cancel>
      <template #title> 查看详情 </template>
      <div>
        <a-space>
          <a-button
            type="outline"
            v-permission="exportRecordDeleteList"
            :loading="loadings"
            @click="exportExcelList"
          >
            <!-- Use the default slot to avoid extra spaces -->
            <template #default>导出</template>
          </a-button>
        </a-space>
        <cardNo style="margin-top: 20px" :tablist="cardList" :load="cardLoading" />
        <TableFooter ref="tableFooterRef" :pagination="paginations" />
      </div>
      <template #footer>
        <a-space />
      </template>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import {
    getPollingLog,
    getPollingLogs,
    recordtDeleteList,
    exportRecordDeleteList,
  } from '@/api/url'
  import { get } from '@/api/http'
  import { usePagination, useRowKey, useTable } from '@/hooks/table'
  import { onMounted, reactive, ref } from 'vue'

  import useCommonStore from '@/store/modules/common'
  import _ from 'lodash-es'

  import cardNo from '@/views/log/compoents/cardNo.vue'

  const table = useTable()

  const userCommon = useCommonStore()

  const pagination = usePagination(doRefresh)

  const paginations = usePagination(cardListFn)

  const seachForm = ref()

  const visible = ref(false)

  const cardLoading = ref(false)

  const loading = ref(false)
  const loadings = ref(false)
  const id = ref()
  const success = ref()

  const admin: any = ref([])
  const channel: any = ref([])
  const series: any = ref([])
  const cardList: any = ref([])

  const form = reactive({
    channelId: '', //渠道id
    state: '', //系列id
    addAddTime: '',
    endAddTime: '',
    addTotal: '',
    endTotal: '',
    addSuccess: '', //      开始成功数量
    endSuccess: '', //       结束成功数量
    addError: '', //       开始失败数量
    endError: '', //     结束失败数量
    addPollingThread: '', //      开始线程数量
    endPollingThread: '',
    pollingTime: '',
  })

  const tables = reactive({
    tableLoading: false,
    bordered: false,
    striped: false,
  })

  const tableColumns: any = reactive({
    list: [
      {
        title: '日志ID',
        key: 'id',
        dataIndex: 'id',
        align: 'center',
        checked: true,
        width: 100,
      },
      {
        title: '渠道',
        key: 'channelId',
        dataIndex: 'channelId',
        align: 'center',
        checked: true,
        width: 100,
      },
      {
        title: '线程数量',
        key: 'pollingThread',
        dataIndex: 'pollingThread',
        align: 'center',
        checked: true,
        width: 100,
      },
      {
        title: '轮询间隔',
        key: 'pollingTime',
        dataIndex: 'pollingTime',
        align: 'center',
        checked: true,
        width: 150,
      },
      {
        title: '轮询数量',
        key: 'total',
        dataIndex: 'total',
        align: 'center',
        checked: true,
        width: 100,
      },
      {
        title: '成功数量',
        key: 'success',
        dataIndex: 'success',
        align: 'center',
        checked: true,
        width: 100,
      },
      {
        title: '失败数量',
        key: 'error',
        dataIndex: 'error',
        align: 'center',
        checked: true,
        width: 100,
      },
      {
        title: '轮询时间',
        key: 'time',
        dataIndex: 'time',
        align: 'center',
        checked: true,
        width: 190,
      },
      {
        title: '成功率',
        key: 'probability',
        dataIndex: 'probability',
        align: 'center',
        checked: true,
        width: 100,
      },
      {
        title: '状态',
        key: 'state',
        dataIndex: 'state',
        align: 'center',
        checked: true,
        width: 100,
      },
      {
        title: '开始轮询时间',
        key: 'addTime',
        dataIndex: 'addTime',
        align: 'center',
        checked: true,
        width: 190,
      },
      {
        title: '结束轮询时间',
        key: 'endTime',
        dataIndex: 'endTime',
        align: 'center',
        checked: true,
        width: 190,
      },
    ],
  })

  const rowKey = useRowKey('id')

  const resetSeach = () => {
    form.addTotal = ''
    form.endTotal = ''
    form.addSuccess = '' //      开始成功数量
    form.endSuccess = '' //       结束成功数量
    form.addError = '' //       开始失败数量
    form.endError = '' //     结束失败数量
    form.addPollingThread = '' //      开始线程数量
    form.endPollingThread = '' //      结束线程数量
    seachForm.value.resetFields()
    doRefresh(1)
  }

  function cardListFn() {
    cardLoading.value = true
    get({
      url: recordtDeleteList,
      data: {
        parentId: id.value,
        success: success.value,
        page: paginations.page,
        size: paginations.pageSize,
      },
    }).then((res) => {
      cardLoading.value = false
      cardList.value = res.data.list
      paginations.setTotalSize((res.data as any).totalSize)
      return res.data.list
    })
  }

  const channels = () => {
    userCommon.channels().then((res: any) => {
      channel.value = res.data
    })
  }

  const exportExcelList = () => {
    loadings.value = true
    userCommon
      .downLoads(exportRecordDeleteList, { parentId: id.value, success: success.value }, '轮询日志')
      .then(() => {
        loadings.value = false
      })
      .catch(() => {
        loadings.value = false
      })
  }

  const exportExcelLists = () => {
    loading.value = true
    userCommon
      .downLoads(getPollingLogs, form, '轮询日志')
      .then(() => {
        loading.value = false
      })
      .catch(() => {
        loading.value = false
      })
  }

  function onUpdateBorder(isBordered: boolean) {
    tables.bordered = isBordered
  }

  function onUpdateStriped(isStriped: boolean) {
    tables.striped = isStriped
  }

  function doRefresh(value?: number) {
    tables.tableLoading = true
    if (value) {
      pagination.page = value
    }
    get({
      url: getPollingLog,
      data: {
        ...form,
        page: pagination.page,
        size: pagination.pageSize,
      },
    }).then((res) => {
      tables.tableLoading = false
      table.handleSuccess(res.data.list)
      pagination.setTotalSize((res.data as any).totalSize)
      return res.data.list
    })
  }

  const adminLists = () => {
    userCommon.adminLists().then((res) => {
      admin.value = res.data
    })
  }

  const seriess = () => {
    userCommon.seriess().then((res) => {
      series.value = res.data
    })
  }

  // //跟踪API开始时间限制结束时间
  // function changeTraceEnd(time: any) {
  //   return time.getTime() > new Date(form.endAddTime).getTime() //大于结束时间的不选
  // }
  // //跟踪API结束时间限制开始时间
  // function changeTraceStart(time: any) {
  //   return time.getTime() < new Date(form.addAddTime).getTime() //小于开始时间的不选
  // }
  onMounted(async () => {
    await doRefresh()
    await adminLists()
    await channels()
    await seriess()
  })
</script>

<style lang="less" scoped>
  :deep(.arco-table-cell-expand-icon) {
    justify-content: center;
  }

  .box {
    overflow: hidden; //超出的文本隐藏
    text-overflow: ellipsis; //用省略号显示
    white-space: nowrap;
  }

  .tabs {
    display: flex;
    justify-content: space-around;
    align-items: center;
    height: 40px;
    margin-bottom: 20px;

    .button {
      box-sizing: border-box;
      padding-bottom: 5px;
    }
  }

  .action {
    color: #009dff;
    border-bottom: 3px solid #009dff;
  }

  .butten {
    padding: 0px 4px;
  }
</style>
